package com.electronic.valid;


import com.cebpubservice.utils.StringUtils;
import com.electronic.exception.ResultCode;
import com.electronic.exception.ServiceException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @Author: IFCA
 * @Description: 验证参数，对象里面使用javax.validation.constraints注解的属性进行验证
 */
public class BeanValidator {

    private static final Validator VALIDATOR;

    static {
        VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
    }

    private BeanValidator() {
    }

    /**
     * 验证对象必填参数
     *
     * @param entity
     * @param groups
     * @param <T>
     * @return 抛出参数验证异常(项目在全局异常处理中进行捕获处理)
     */
    public static <T> void validateReturnException(T entity, Class<?>... groups) {
        String msg = convertErrorMsg(entity, groups);
        if (StringUtils.isEmpty(msg)) {
            return;
        }
        throw new ServiceException(ResultCode.ERROR_PARAM, msg);
    }

    /**
     * 验证对象必填参数
     *
     * @param entity
     * @param groups
     * @param <T>
     * @return
     */
    private static <T> String convertErrorMsg(T entity, Class<?>... groups) {
        Set<ConstraintViolation<T>> constraintViolations = VALIDATOR.validate(entity, groups);
        if (constraintViolations.isEmpty()) {
            return null;
        }
        return constraintViolations.iterator().next().getMessage();
    }


}
